import axios from 'axios'
const service = axios.create({
  baseURL: '/api/steam',
  timeout: 60000
})

// request 拦截器
service.interceptors.request.use(
  config => {
    const access_token = localStorage.getItem("access_token");
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data'; // 如果是 FormData 类型，则设置 Content-Type
    } else if (config.headers['Content-Type'] === 'application/octet-stream;charset=UTF-8') {
      config.headers['Content-Type'] = 'application/octet-stream;charset=UTF-8';
    } else {
      config.headers.Authorization = access_token;
      config.headers['Content-Type'] = 'application/json'; // 默认为 application/json
    }
    return config;
  },
  error => {
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

// 封装具体的请求方法: 四种请求类型不和下面的3和4标题内容放在一起
export const get = (url, params) => {
  return service.get(url, { params });
};

export const post = (url, data) => {
  return service.post(url, data);
};

export const put = (url, data) => {
  return service.put(url, data);
};

export const postFormData = (url, formData) => {
  return service.post(url, formData);
};

export const postWithParams = (url, params) => {
  const queryString = Object.keys(params).map(key => {
    const encodedKey = key;
    const encodedValue = (params[key]);
    return `${encodedKey}=${encodedValue}`;
  }).join('&');
  const fullUrl = `${url}?${queryString}`;
  return service.post(fullUrl, params);
};

export const getBlob = (url, config = {}) => {
  return service.get(url, { ...config, responseType: 'blob' });
};


export default service